﻿using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnEx
    {
        public static bool VertexMapRepair(this Mesh source, Mesh target, out int[] mapping, int passes, float maxDistance = 1e-04f)
        {
            if (!HasMinimumRequirements(source, true) || !HasMinimumRequirements(target, true) || !SkinnInternalAsset.Asset || !SkinnInternalAsset.Asset.HasShaders())
            {
                mapping = null;
                return false;
            }

            var targetMesh = target;
            var sourceMesh = source;

            VertexWrapper.SetData(
                targetMesh.vertices,
                sourceMesh.vertices,

                targetMesh.triangles,
                sourceMesh.triangles,

                IsNullOrEmpty(targetMesh.bindposes) ? 0 : targetMesh.bindposes.Length,
                IsNullOrEmpty(sourceMesh.bindposes) ? 0 : sourceMesh.bindposes.Length,

                targetMesh.GetNormalsRecalculated(),
                sourceMesh.GetNormalsRecalculated(),

                targetMesh.GetTangentsRecalculated(),
                sourceMesh.GetTangentsRecalculated(),

                targetMesh.GetSubMeshIndices(),
                sourceMesh.GetSubMeshIndices(),

                targetMesh.uv,
                sourceMesh.uv,

                targetMesh.boneWeights,
                sourceMesh.boneWeights,
                null,
                null
                );

            VertexWrapper.CompareSubMesh = SkinnInternalAsset.Asset.vetexImporterSettings.compareSubMesh;
            VertexWrapper.CompareUV = SkinnInternalAsset.Asset.vetexImporterSettings.compareUV;
            VertexWrapper.CompareNormals = SkinnInternalAsset.Asset.vetexImporterSettings.compareNormal;
            VertexWrapper.CompareWeights = false;
            VertexWrapper.CompareTangents = SkinnInternalAsset.Asset.vetexImporterSettings.compareTangent;
            VertexWrapper.MaxDistance = maxDistance;

            VertexWrapper.SearchMultiPass();
            VertexWrapper.FallbackPass();

            VertexWrapper.IndexRetargetingPass();
            VertexWrapper.MappingIndices.GetData(VertexWrapper.mapping);

            mapping = VertexWrapper.mapping;
            //VertexWrapper.DistancePass();

            VertexWrapper.ReleaseBuffers();
            return mapping[0] > -1;
        }

    }
}
